/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package radiostation;

import java.awt.Color;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import model.Album;
import model.Song;

/**
 *
 * @author tg
 */
public class ListArtistAlbumForm extends javax.swing.JFrame {
    
    /**
     * Creates new form ListArtistAlbumForm
     */
    EntityManager em;
    int selectedRow;    
    Album album;
    
    public ListArtistAlbumForm() {
        em = DBManager.em;
        if (!em.getTransaction().isActive()) {
            em.getTransaction().begin();
        }
        initComponents();
        manageButtons();
        DBManager.centerOnScreen(this);
        this.jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        TableCellRenderer rendererFromHeader = jTable1.getTableHeader().getDefaultRenderer();
        JLabel Id = (JLabel)rendererFromHeader;
        Id.setHorizontalAlignment(JLabel.CENTER);

        JTableHeader header = jTable1.getTableHeader();
        header.setForeground(Color.red);

        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        jTable1.getColumnModel().getColumn(2).setCellRenderer(centerRenderer);
        jTable1.getColumnModel().getColumn(2).setCellRenderer(new DateCellRenderer());
        jTable1.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
        jTable1.getColumnModel().getColumn(3).setCellRenderer(centerRenderer);
        jTable1.getColumnModel().getColumn(4).setCellRenderer(centerRenderer);
    }

        private void manageButtons() {
        selectedRow = jTable1.getSelectedRow();
        jButton2.setEnabled(selectedRow >= 0);
        jButton3.setEnabled(selectedRow >= 0);

        if (selectedRow >= 0) {          
            album = albumList.get(jTable1.convertRowIndexToModel(selectedRow));
        }
        }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        albumQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("SELECT a FROM Album a WHERE a.fartistId IS NOT NULL order by a.title");
        albumList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(albumQuery.getResultList());
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Πίνακας Άλμπουμ Καλλιτεχνών");

        jLabel1.setForeground(new java.awt.Color(0, 51, 255));
        jLabel1.setText("Άλμπουμ Καλλιτεχνών:");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        jButton1.setText("Εισαγωγή");
        jButton1.setToolTipText("Πατήστε για Εισαγωγή νέου Άλμπουμ Καλλιτέχνη");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit.png"))); // NOI18N
        jButton2.setText("Επεξεργασία");
        jButton2.setToolTipText("Πατήστε για Επεξεργασία υπάρχοντος Άλμπουμ Καλλιτέχνη");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        jButton3.setText("Διαγραφή");
        jButton3.setToolTipText("Πατήστε για Διαγραφή Άλμπουμ Καλλιτέχνη");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/stock_exit.png"))); // NOI18N
        jButton4.setText("Έξοδος");
        jButton4.setToolTipText("Πατήστε για Επιστροφή στο Κεντρικό Μενού");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, albumList, jTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${id}"));
        columnBinding.setColumnName("Κωδικός");
        columnBinding.setColumnClass(Long.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${title}"));
        columnBinding.setColumnName("Τίτλος");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${releasedate}"));
        columnBinding.setColumnName("Ημερ.Κυκλοφορίας");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${type}"));
        columnBinding.setColumnName("Τύπος");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${disknumber}"));
        columnBinding.setColumnName("Αρ.Δίσκων");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fartistId.artisticname}"));
        columnBinding.setColumnName("Καλλιτέχνης");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${flabelId.name}"));
        columnBinding.setColumnName("Εταιρεία Παραγωγής");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        if (jTable1.getColumnModel().getColumnCount() > 0) {
            jTable1.getColumnModel().getColumn(0).setMaxWidth(70);
            jTable1.getColumnModel().getColumn(1).setMaxWidth(250);
            jTable1.getColumnModel().getColumn(2).setMaxWidth(170);
            jTable1.getColumnModel().getColumn(3).setMaxWidth(70);
            jTable1.getColumnModel().getColumn(4).setMaxWidth(80);
            jTable1.getColumnModel().getColumn(5).setMaxWidth(150);
            jTable1.getColumnModel().getColumn(6).setMaxWidth(150);
        }

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(79, 79, 79)
                        .addComponent(jButton1)
                        .addGap(27, 27, 27)
                        .addComponent(jButton2)
                        .addGap(30, 30, 30)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 318, Short.MAX_VALUE)
                        .addComponent(jButton4)
                        .addGap(61, 61, 61))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jScrollPane1)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(5, 5, 5)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3)
                    .addComponent(jButton1)
                    .addComponent(jButton4))
                .addGap(15, 15, 15))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
       
       Album alb = new Album ();
        em.persist(alb);      
        EditArtistAlbumForm eaaf = new EditArtistAlbumForm(alb, false);       
        eaaf.setVisible(true);
        thisFrame = this;
        thisFrame.setEnabled(false);
        
        eaaf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
                if (((MyWindowEvent)arg0).exitAndSave) {
                    manageButtons();
                    em.persist(alb);  
                    albumList.add(alb);
                    em.getTransaction().commit();
                    java.util.Collection data = albumQuery.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);  
                    }
                    albumList.clear();
                    albumList.addAll(data);

                    int row = albumList.size() - 1;
                    jTable1.setRowSelectionInterval(row, row);
                    jTable1.scrollRectToVisible(jTable1.getCellRect(row, 0, true));
                    thisFrame.setEnabled(true);
                }
                else {
                    thisFrame.setEnabled(true);
                    em.getTransaction().rollback();
                    em.getTransaction().begin();
                    java.util.Collection data = albumQuery.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);  
                    }
                    albumList.clear();
                    albumList.addAll(data);
                    manageButtons();
            }
        }

            public void windowActivated(WindowEvent arg0) {

                System.out.println("Window Activated");
            }

            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }

            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }

            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }

            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }

            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened2");

            }
        });   
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
               // TODO add your handling code here:
        selectedRow = jTable1.getSelectedRow();
        alb = albumList.get(jTable1.convertRowIndexToModel(selectedRow));
        EditArtistAlbumForm eaaf = new EditArtistAlbumForm(alb, true);
        eaaf.setVisible(true);
        thisFrame = this;
        thisFrame.setEnabled(false);

        eaaf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
                if (((MyWindowEvent)arg0).exitAndSave) {
                    em.persist(alb);
                    albumList.set(selectedRow,alb);
                    em.getTransaction().commit();
                    java.util.Collection data = albumQuery.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);  
                    }
                    albumList.clear();
                    albumList.addAll(data);
                    thisFrame.setEnabled(true);
                }
                else {
                    thisFrame.setEnabled(true);
                    em.getTransaction().rollback();
                    em.getTransaction().begin();
                    java.util.Collection data = albumQuery.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);  
                    }
                    albumList.clear();
                    albumList.addAll(data);
                    manageButtons();
            }
        }  
            public void windowActivated(WindowEvent arg0) {

                System.out.println("Window Activated");
            }

            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }

            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }

            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }

            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }

            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened2");

            }
        });
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
      // TODO add your handling code here:
        if (!em.getTransaction().isActive()) {
            em.getTransaction().begin();
        }
        selectedRow = jTable1.getSelectedRow();
        album = albumList.get(jTable1.convertRowIndexToModel(selectedRow));
        
        if (selectedRow>=0){
            int c = JOptionPane.showConfirmDialog(null, "Επιθυμείτε σίγουρα να διαγράψετε το Άλμπουμ " + album.getTitle() + "?", "Διαγραφή Συγκροτήματος",JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (c == 0){ 
                Album alb = albumList.get(jTable1.convertRowIndexToModel(selectedRow));
                
                for (Song song : alb.getSongList()){
                    song.setFalbumId(null);
                } 
                
                albumList.remove(alb);
                em.remove(alb);
                em.getTransaction().commit(); 
                JOptionPane.showMessageDialog(null, "Η Διαγραφή του Άλμπουμ έγινε με επιτυχία!", "ΕΠΙΤΥΧΗΣ ΔΙΑΓΡΑΦΗ", JOptionPane.INFORMATION_MESSAGE);
            }
            manageButtons();
        }
        else{
            JOptionPane.showMessageDialog(null, "Δεν έχετε επιλέξει Άλμπουμ για Διαγραφή.", "ΑΝΕΠΙΤΥΧΗΣ ΔΙΑΓΡΑΦΗ", JOptionPane.INFORMATION_MESSAGE);        
        }
    }//GEN-LAST:event_jButton3ActionPerformed

      private void closeMe(boolean exitAndSave) {
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED, exitAndSave);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
        }
        this.setVisible(false);
    }
      
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        closeMe(true);
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // TODO add your handling code here:
        manageButtons();
    }//GEN-LAST:event_jTable1MouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.util.List<model.Album> albumList;
    private javax.persistence.Query albumQuery;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
   
   JFrame thisFrame;
   Album alb;
    
}
